import store from '@/store'
var rtc = null
var isRTCInitialized = false

// 初始化RTC
export async function initRTC(localVideo, remoteVideo, to) {
  if (rtc != null || isRTCInitialized) {
    return
  }
  isRTCInitialized = true

  // 创建RTCPeerConnection对象
  rtc = new RTCPeerConnection({
    iceServers: [
      { urls: 'stun:stun.l.google.com:19302' },
      { urls: 'stun:stun1.l.google.com:19302' },
      { urls: 'stun:stun2.l.google.com:19302' },
      { urls: 'stun:stun3.l.google.com:19302' },
      { urls: 'stun:stun4.l.google.com:19302' },
      { urls: 'stun:stunserver.org' },
      { urls: 'stun:stun.xten.com' },
      { urls: 'turn:numb.viagenie.ca', username: 'webrtc@live.com', credential: 'muazkh' },
    ],
    sdpSemantics: 'unified-plan', // 使用统一计划语义
  })

  // 打开摄像头并添加本地视频流
  try {
    const stream = await openMeCamera(localVideo)
    stream.getTracks().forEach((track) => {
      console.log('Adding track:', track)
      rtc.addTrack(track, stream)
    })
  } catch (error) {
    console.error('Error opening camera:', error)
  }

  // 监听ice状态变化
  rtc.onicecandidate = (e) => {
    if (e.candidate) {
      setTimeout(() => {
        sendMessage({ candidate: e.candidate }, 8, to)
      }, 2500)
    }
  }

  // 监听远端视频流
  rtc.ontrack = (event) => {
    if (event.streams.length > 0) {
      remoteVideo.srcObject = event.streams[0]
    }
  }
}

// 发起请求视频
export function requestVideo(to) {
  sendMessage('', 5, to)
}

// offer阶段
export function offer(localVideo, remoteVideo, to) {
  return new Promise(async (resolve, reject) => {
    await initRTC(localVideo, remoteVideo, to)

    try {
      const offer = await rtc.createOffer()
      console.log('Created offer:', offer.sdp)
      await rtc.setLocalDescription(offer)
      sendMessage(offer, 6, to)
      resolve(offer)
    } catch (err) {
      console.error('Error creating offer:', err)
      reject(err)
    }
  })
}

// answer阶段
export function answer(localVideo, remoteVideo, offer, to) {
  return new Promise(async (resolve, reject) => {
    await initRTC(localVideo, remoteVideo, to)

    try {
      console.log('Received offer:', offer.sdp)
      offer.sdp += '\n'
      await rtc.setRemoteDescription(new RTCSessionDescription(offer))
      const answer = await rtc.createAnswer()
      console.log('Created answer:', answer.sdp)
      await rtc.setLocalDescription(answer)
      sendMessage(answer, 7, to)
      resolve(answer)
    } catch (err) {
      console.error('Error in answer phase:', err)
      reject(err)
    }
  })
}

// 本地收到并设置answer
export function localSetAnswer(answer) {
  return new Promise(async (resolve, reject) => {
    try {
      console.log('Setting remote description:', answer.sdp)
      answer.sdp += '\n'
      await rtc.setRemoteDescription(new RTCSessionDescription(answer))
      resolve(answer)
    } catch (e) {
      console.error('Error setting remote description:', e)
      reject(e)
    }
  })
}

// 打开本地摄像头
async function openMeCamera(localVideo) {
  return new Promise((resolve, reject) => {
    navigator.mediaDevices
      .getUserMedia({
        video: true,
        audio: true,
      })
      .then(function (stream) {
        localVideo.srcObject = stream
        resolve(stream)
      })
      .catch(function (error) {
        reject(error)
      })
  })
}

// 交换candidate
export function setCandidate(candidate) {
  return new Promise((resolve, reject) => {
    if (!candidate || !rtc || !rtc.remoteDescription) {
      console.warn('RTCPeerConnection not initialized or remote description not set')
      return
    }
    try {
      var newCandidate = new RTCIceCandidate({
        sdpMLineIndex: candidate.sdpMLineIndex,
        candidate: candidate.candidate,
        sdpMid: candidate.sdpMid,
      })

      rtc
        .addIceCandidate(newCandidate)
        .then(() => resolve(newCandidate))
        .catch((error) => {
          console.error('Error adding ICE candidate:', error)
          reject(error)
        })
    } catch (e) {
      console.error('Error creating ICE candidate:', e)
      reject(e)
    }
  })
}

// 关闭RTC
export function closeRTC(localVideo) {
  if (rtc) {
    // 获取本地流并停止所有轨道
    const localStream = localVideo.srcObject
    if (localStream) {
      localStream.getTracks().forEach((track) => {
        track.stop()
      })
    }
    0
    // 清除视频元素的 srcObject
    localVideo.srcObject = null
    // 关闭 RTCPeerConnection
    rtc.close()
    rtc = null
    isRTCInitialized = false
  }
}
// 发送消息
function sendMessage(message, type, to) {
  var newMsg = {
    to: to,
    type: type,
    from: store.getters.id,
    content: message,
  }
  store.dispatch('message/sendMessage', newMsg)
}
